import React from 'react';
import { Table, Divider, Modal } from 'antd';
import Page from 'components/common/Page';
import SearchBar from './SearchBar';
import { model } from 'utils/model';
import AddModal from './Modals/AddModal';
import fields from './fields';

@model('companyManage')
class CompanyManage extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      visAdd: false,
      visResetPass: false,
      record: {}
    };
    this.settingHandler = this.settingHandler.bind(this);
    this.del = this.del.bind(this);
  }

  del(params) {
    const { del, loading } = this.props;
    Modal.confirm({
      title: '你确定要执行此操作？',
      cancelText: '取消',
      okText: '确定',
      confirmLoading: loading.del,
      onOk() {
        del(params);
      }
    });
  }


  // 扩展字段
  extraFields() {
    const settingHandler = this.settingHandler;
    const del = this.del;
    const extra = [
      {
        title: '操作',
        key: 'action',
        render: (text, record) => (
          <span>
            <a href="javascript:;" onClick={() => settingHandler('visAdd', true, record)}>修改</a>
            <Divider type="vertical" />
            {/* <a href="javascript:;" onClick={() => settingHandler('visResetPass', true, record)}>修改密码</a>
            <Divider type="vertical" /> */}
            <a href="javascript:;" onClick={() => del({ id: record.id })}>删除</a>
          </span>
        )
      }
    ];
    return fields.concat(extra);
  }
  settingHandler(type, value, record = {}) {
    this.setState({
      record,
      [type]: value
    });
  }

  render() {
    const {
      config, add, edit, loading,
      getList, goPage, getDetail, details,
      updateState } = this.props;
    const { visAdd, record } = this.state;
    const { pagination, list } = config;

    const tableProps = {
      pagination: {
        ...pagination,
        onChange: (current) => {
          goPage(current);
          getList();
        }
      },
      loading: loading.list,
      rowKey: (record, index) => index,
      dataSource: list,
      columns: this.extraFields()
    };
    const searchProps = {
      record,
      add: () => this.settingHandler('visAdd', true),
      onSearch(params) {
        goPage(1);
        getList(params);
      }
    };
    const addProps = {
      getDetail,
      record,
      getList,
      details,
      loading: loading.add,
      onCancel: () => {
        this.settingHandler('visAdd', false);
        updateState({ details: {} });
      },
      onOK: record.id ? edit : add
    };

    return (
      <Page inner>
        <div>
          <SearchBar {...searchProps} />
          <Table {...tableProps} style={{ marginTop: 20 }} />
          {visAdd && <AddModal {...addProps} />}
        </div>
      </Page>
    );
  }
}

export default CompanyManage;
